import { DATA_TYPE_ALIAS } from './utils'
import Text from './modules/text'

const path = require('path')

const modules = {
  text: Text
}
const files = require.context('./modules', false, /\.js$/)
files.keys().forEach(key => {
  const module = files(key).default
  if (module !== undefined) {
    var name = path.basename(key, '.js')
    modules[name] = module
    var alias = DATA_TYPE_ALIAS[name] || []
    alias.map(aname => {
      modules[aname] = module
    })
  }
})

const FormatterView = {
  name: 'FormatterView',
  functional: true,
  props: {
    row: Object,
    options: Object,
    index: Number,
    column: [String, Array],
    format: {
      type: Object,
      default: null
    }
  },
  render: (h, ctx) => {
    const { format, column, row, options } = ctx.props
    var _opts = options || {}
    var _format = format || {}
    if (_format.options) {
      _opts = Object.assign({}, options, _format.options)
    }
    var formatType = _format.type || 'text'
    if (Array.isArray(column)) {
      var value = column.map(attr => {
        return row[attr]
      })
    } else {
      value = row[column]
    }
    return h(
      modules[formatType],
      {
        props: {
          value: value,
          row: row,
          column: column,
          options: _opts
        },
        on: {
          click: name => {
            var listeners = ctx.listeners['click']
            if (listeners && typeof listeners === 'function') {
              listeners({
                type: formatType,
                name: name,
                row: row
              })
            }
          }
        }
      },
      ctx.children
    )
  }
}

export default FormatterView
